﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Manager;
using System.IO;
using System.Text;
using ExtAspNet;
namespace HealthSystem
{
    public partial class test : BasePage
    {
        HW_SchoolManager manager = new Manager.HW_SchoolManager();
        
        protected void Page_Load(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference());
            if (!IsPostBack)
            {
                string path = System.Configuration.ConfigurationManager.AppSettings["SignDir"].ToString();
                string id = Request["id"].ToString();
                var school = manager.GetById(id);
                if (school.Permit != true)
                {
                    Alert.Show("该学校未授权!");
                    return;
                }
                string name = school.Name + ".gdsx";
                //name = System.Text.Encoding.GetEncoding("gb2312");
                //string filename = path + "\\" + name;
                string filename = path + "\\" + school.SchoollCode+".gdsx";
                if (CustomerProfile.RoleId == 1001)
                {
                    XMLHelper xmlHelper = new XMLHelper();
                    xmlHelper.CreateValidateFile(school);
                    DownloadFile(name, filename);
                    //xmlHelper.DeleteSignFile(school);
                }
                else if (CustomerProfile.RoleId == 2000)
                {

                    if (CustomerProfile.OrgId == school.OrgCode)
                    {
                        XMLHelper xmlHelper = new XMLHelper();
                        xmlHelper.CreateValidateFile(school);
                        DownloadFile(name, filename);
                        //xmlHelper.DeleteSignFile(school);
                    }
                    else
                    {
                        ExtAspNet.Alert.Show("你没有权限");
                        return;
                    }
                }
                else
                {
                    ExtAspNet.Alert.Show("你没有权限");
                    return;
                }
               
            }
            
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="WebForm"></param>
        /// <param name="FileNameWhenUserDownload"></param>
        /// <param name="FilePath"></param>
        public void DownloadFile(string fileName, string filePath)
        {
            if (System.IO.File.Exists(filePath))
            {
                //以字符流的形式下载文件
                FileStream fs = new FileStream(filePath, FileMode.Open);
                byte[] bytes = new byte[(int)fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                fs.Close();
                Response.ContentType = "application/octet-stream";
                //通知浏览器下载文件而不是打开
                Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                Response.BinaryWrite(bytes);
                
                Response.Flush();
                Alert.Show("下载完毕");
                Response.End();
                
                //Response.ContentType = "application/x-zip-compressed";
                //Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
                //Response.TransmitFile(filePath);

                //string encodefileName = Server.UrlEncode(fileName);
                //FileInfo fileInfo = new FileInfo(filePath);
                //Response.Clear();
                //Response.ClearContent();
                //Response.ClearHeaders();
                //Response.AddHeader("Content-Disposition", "attachment;filename=" + encodefileName);
                //Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                //Response.AddHeader("Content-Transfer-Encoding", "binary");
                //Response.ContentType = "application/octet-stream";
                //Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                //Response.WriteFile(fileInfo.FullName);
                //Response.Flush();
                //HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
            else
            {
                ExtAspNet.Alert.Show("文件不存在");
            }





            //            System.IO.FileInfo info = new System.IO.FileInfo(filePath); 
            //            long fileSize = info.Length; 
            //            Response.Clear(); 
            //            Response.ContentType = "application/x-zip-compressed"; 
            //            Response.AddHeader("Content-Disposition", "attachment;filename="+ fileName); 
            ////不指明Content-Length用Flush的话不会显示下载进度 
            //            Response.AddHeader("Content-Length", fileSize.ToString()); 
            //            Response.TransmitFile(filePath, 0, fileSize); 
            //            Response.Flush(); 
            //            Response.Close(); 
        }
        /// <summary>
        /// Encodes non-US-ASCII characters in a string.
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ToHexString(string s)
        {
            char[] chars = s.ToCharArray();
            StringBuilder builder = new StringBuilder();
            for (int index = 0; index < chars.Length; index++)
            {
                bool needToEncode = NeedToEncode(chars[index]);
                if (needToEncode)
                {
                    string encodedString = ToHexString(chars[index]);
                    builder.Append(encodedString);
                }
                else
                {
                    builder.Append(chars[index]);
                }
            }

            return builder.ToString();
        }

        /// <summary>
        /// Determines if the character needs to be encoded.
        /// </summary>
        /// <param name="chr"></param>
        /// <returns></returns>
        private static bool NeedToEncode(char chr)
        {
            string reservedChars = "$-_.+!*'(),@=&";

            if (chr > 127)
                return true;
            if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0)
                return false;

            return true;
        }

        /// <summary>
        /// Encodes a non-US-ASCII character.
        /// </summary>
        /// <param name="chr"></param>
        /// <returns></returns>
        private static string ToHexString(char chr)
        {
            UTF8Encoding utf8 = new UTF8Encoding();
            byte[] encodedBytes = utf8.GetBytes(chr.ToString());
            StringBuilder builder = new StringBuilder();
            //for (int index = 0; index < encodedBytes.Length; index++)
            //{
                builder.AppendFormat("%{0}", Convert.ToBase64String(encodedBytes));
            //}

            return builder.ToString();
        }
    }
}